package com.itheima.day20.demo05;

import java.io.*;

public class CopyFiles {
    public static final String SOURCE_FILE = "D:\\day04\\A星算法";// 填写【源文件夹】的绝对路径
    public static final String DES_FILE = "D:\\day04\\123";// 填写【目标文件夹】的绝对路径(若不存在，自动创建)

    public static void main(String[] args) {
        copyDir(new File(SOURCE_FILE));
    }

    public static void copyDir(File file) {
        String newPath = DES_FILE + file.getPath().substring(SOURCE_FILE.length());
        File tempFile = new File(newPath);
        if (file.isDirectory()) {
            if (!tempFile.exists()) {
                tempFile.mkdir();
                System.out.println("创建文件夹:" + tempFile.getName());
            }
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return pathname.getName().endsWith(".avi");
                }
            });
            for (File f : files) {
                copyDir(f);
            }
        } else {
            copyFile(file.getPath(), newPath);
        }
    }

    public static void copyFile(String sourceFile, String desFile) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(sourceFile);
            fos = new FileOutputStream(desFile);
            byte[] bys = new byte[32];
            int len = 0;
            while ((len = fis.read(bys, 0, bys.length)) != -1) {
                fos.write(bys, 0, len);
            }
            System.out.println("文件复制完成！" + new File(desFile).getName());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                    fos = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                        fis = null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
